//
//  FMContactTool.m
//  flutter_device_info_plugin
//
//  Created by 小琦 on 2025/3/2.
//

#import "FMContactTool.h"
#import <Contacts/Contacts.h>
#import <Contacts/CNLabeledValue.h>
#import <ContactsUI/ContactsUI.h>
#import "FMDeniedAccessAlertTool.h"
#import "FMContactController.h"

@implementation FMContactTool

- (void)openContact {
    CNContactStore *contactStore = [[CNContactStore alloc] init];
    [contactStore requestAccessForEntityType:CNEntityTypeContacts completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            [self popContacts];
        } else {
            [self showDeniedPop];
        }
    }];
}

- (void)popContacts{
    dispatch_async(dispatch_get_main_queue(), ^{
        FMContactController *vc = [[FMContactController alloc] init];
        vc.contactHandle = ^(NSString * name, NSString * phone) {
            NSDictionary *dic = @{
                @"name" : name,
                @"phone" : phone
            };
            self.contactHandle(dic);
        };
        UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
        [rootViewController presentViewController:vc animated:YES completion:nil];
    });
}

- (void)showDeniedPop {
    dispatch_async(dispatch_get_main_queue(), ^{
        [FMDeniedAccessAlertTool showMessage:@"Please enable access to Contacts in Settings."];
    });
}

- (void)getContactInfo:(void (^)(NSArray * _Nonnull))completion {
    
    NSArray *keys = @[CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey,CNContactBirthdayKey,CNContactEmailAddressesKey];
    
    CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:keys];
    
    CNContactStore *store = [[CNContactStore alloc] init];

    __block NSMutableArray *dataList = [NSMutableArray array];
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSError *error = nil;
        [store enumerateContactsWithFetchRequest:request error:nil usingBlock:^(CNContact * _Nonnull contact, BOOL * _Nonnull stop) {

                NSString *given = contact.givenName;
                NSString *family = contact.familyName;
                NSString *fullName = [NSString stringWithFormat:@"%@ %@",given,family];

                NSArray *phoneList = contact.phoneNumbers;
                NSMutableArray *phoneArr = [NSMutableArray array];
                for (CNLabeledValue *labelValue in phoneList) {
                    CNPhoneNumber *phoneNumber = labelValue.value;
                    [phoneArr addObject:phoneNumber.stringValue];
                }
                NSString *phoneText = [phoneArr componentsJoinedByString:@","];

                NSString *emailText = @"";
                for (CNLabeledValue *email in contact.emailAddresses) {
                    NSString *emailString = email.value;
                    emailText = emailString;
                }

                NSString *birthDayText = @"";
                if (contact.birthday) {
                    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
                    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
                    birthDayText = [dateFormatter stringFromDate:contact.birthday.date];
                }

                NSMutableDictionary * myDict = [NSMutableDictionary dictionary];

                [myDict setValue:phoneText.length ? phoneText : @"" forKey:@"bold"];
                [myDict setValue:birthDayText.length ? birthDayText : @"" forKey:@"courtyard"];
                [myDict setValue:emailText.length ? emailText : @"" forKey:@"papa"];
                [myDict setValue:fullName.length ? fullName : @"" forKey:@"planned"];
                [myDict setValue:@"" forKey:@"pressed"];

                NSTimeInterval currentTimestamp = [[NSDate date] timeIntervalSince1970];
                long long timestampInMilliseconds = (long long)currentTimestamp;
                NSString *currentTimestampStr = [NSString stringWithFormat:@"%lld",timestampInMilliseconds];
                [myDict setValue:currentTimestampStr forKey:@"example"];
                [myDict setValue:currentTimestampStr forKey:@"narration"];

                [dataList addObject:myDict];

            }];

            completion(dataList);
    });
}

@end
